The Exception class is the base class for all exceptions in Java. All custom exceptions should inherit from
this class. Examples include:
ArithmeticException - Dividing a number by zero.
NullPointerException - Accessing a method or property of a null object.
Types of Exceptions
Checked Exceptions: Exceptions checked at compile-time, such as IOException and
SQLException. These must be handled using try-catch or declared using throws.
Unchecked Exceptions: Exceptions that occur at runtime, like NullPointerException and
ArithmeticException. These are subclasses of RuntimeException.
Exception Handling Keywords
try: Contains code that may throw exceptions.
catch: Catches and handles exceptions thrown by the try block.
throw: Used to explicitly throw an exception.
throws: Declares exceptions a method may throw.
finally: Always executes important code regardless of exception occurrence.
User-defined Exceptions
Custom exceptions can be created by extending the Exception class.
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
Example Code Demonstrating Exception Handling
import java.io.*;
class TestExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Caught Arithmetic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
2. Viva/Interview Questions
An exception is an unexpected event that disrupts the normal flow of a program's
instructions. Java provides various mechanisms to handle these exceptions.
Checked Exceptions: Exceptions that are checked at compile-time (e.g., IOException,
SQLException). Unchecked Exceptions: Exceptions that are not checked at compile-time (e.g., NullPointerException,
ArithmeticException).
User-defined exceptions are custom exceptions created by the programmer by extending the
Exception class.
try: The block of code that may throw an exception. catch: Handles the exception thrown by the try block. throw: Used to explicitly throw an exception. throws: Declares exceptions that can be thrown by a method. finally: Executes important code after the try-catch block, regardless of exception occurrence.
No, the finally block is always executed unless the program terminates using
System.exit().
throw: Used to explicitly throw an exception within a method. throws: Used in method declaration to specify the exceptions a method can throw.